package com.xzj.getway.util;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * 公用方法集中类
 *
 * @author xiazunjun
 * @date 2023/8/3 9:35
 */
@Slf4j
public class Md5Util {

    /**
     * 正序排列map中的keu值
     *
     * @return
     * @author xiazunjun
     * @date 2023/4/25 10:06
     */
    public static Object[] sortMapKey(Set sortKeys) {
        Object[] result = sortKeys.toArray();
        Arrays.sort(result);
        return result;
    }

    /**
     * 字符串进行MD5值计算
     *
     * @return
     * @author xiazunjun
     * @date 2023/4/26 8:34
     */
    public static String objectToMd5(String jsonObject, String... excludeKeys) {
        TreeMap paramTreeMap = JSON.parseObject(jsonObject, TreeMap.class);
        if (excludeKeys != null) {
            List<String> dedupExcludeKeys = Arrays.asList(excludeKeys);
            if (!dedupExcludeKeys.isEmpty()) {
                for (String dedupExcludeKey : dedupExcludeKeys) {
                    paramTreeMap.remove(dedupExcludeKey);
                }
            }
        }
        String paramTreeMapJSON = JSON.toJSONString(paramTreeMap);
        String md5deDupParam = jdkMD5(paramTreeMapJSON);
        log.debug("md5deDupParam = {}, excludeKeys = {} {}", md5deDupParam, Arrays.deepToString(excludeKeys),
            paramTreeMapJSON);
        return md5deDupParam;
    }

    private static String jdkMD5(String src) {
        String res = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] mdBytes = messageDigest.digest(src.getBytes());
            res = printHexBinary(mdBytes);
        } catch (Exception e) {
            log.error("", e);
        }
        return res;
    }

    private static String printHexBinary(byte[] hash) {
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * Map中根据key批量删除键值对
     * @param map 对象map
     * @param notExcludeKey 无需删除的key
     * @param <K>
     * @param <V>
     * @return
     */
    public static <K, V> Map removeEntries(Map<K, V> map, K notExcludeKey) {
        Iterator<K> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            K key = iterator.next();
            // 如果key 刚好在要排除的key的范围中
            if (!key.equals(notExcludeKey)) {
                iterator.remove();
                map.remove(key);
            }
        }
        return map;
    }
}
